//
//  NoteMenuController.swift
//  poetry
//
//  Created by YL-Hong on 2022/12/16.
//

import UIKit

protocol NoteMenuDelegate:AnyObject {
    func noteMenu(menuControl:NoteMenuController,didSelectItem type:NoetMenuType)
}

enum NoteMenuArrowDirection:Int {
    case down = 0
    case up = 1
}

class NoteMenuController: UIView {

    weak var delegate:NoteMenuDelegate?
    
    private let titles = ["写笔记","复制","划线","勘误"]
    private let icons = ["note_icon_write","note_icon_copy","note_icon_white_line","note_icon_errata"]
    
    private let srcDownArrow = UIImage(named: "note_menu_downArrow")!
    
    private let menuWidth:CGFloat = 241.0
    private let menuHeight:CGFloat = 61.0
    static let menuSuperHeight:CGFloat = 68.0 + 50.0
 
    //划线
    private var textLineItem:NoteMenuItem = NoteMenuItem()
    private var isDeleteLine:Bool = false
    //底色
    static let selectColor:UIColor = UIColor(hexString: "#FAE3BA")
    
    var bgMenuTapBlock:(()->())?
    
    var lineClickItems:[UIButton] = []
    
   static let LineTypeKey:String = "LineTypeKey"
   static var lineType: NoetMenuType {
        get {
            var value = UserDefaults.standard.integer(forKey: LineTypeKey)
            if  value <= 0 {
                value = NoetMenuType.solid_line.rawValue
            }
            return NoetMenuType.init(rawValue: value) ?? .solid_line
        }
        set {
            UserDefaults.standard.setValue(newValue.rawValue, forKey: LineTypeKey)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        lineClickItems.removeAll()
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(menubgTapClick(tap:)))
        self.addGestureRecognizer(tap)
        
        downArrowImageV.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 15, height: 7))
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(50)
        }
        
        menuContentView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: menuWidth, height: menuHeight))
//            make.top.equalToSuperview()
            make.bottom.equalTo(downArrowImageV.snp.top)
            make.centerX.equalTo(downArrowImageV)
        }
        
        editTextView.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: menuWidth * 0.75, height: 50))
            make.bottom.equalTo(menuContentView.snp.top)
            make.right.equalTo(menuContentView)
        }
        
        let itemWidth = menuWidth / 4
        let itemHeight = menuHeight - 26
        let itemSize = CGSize(width: itemWidth, height: itemHeight)
        
        for (i,title) in titles.enumerated() {
            let menuItem = NoteMenuItem()
            menuItem.titleLab.text = title
            menuItem.tag = i + 100
            menuItem.topImageV.image = UIImage(named: icons[i])
            menuContentView.addSubview(menuItem)
            if i == 2 {
                textLineItem = menuItem
            }
            
            menuItem.snp.makeConstraints { make in
                make.size.equalTo(itemSize)
                make.centerY.equalToSuperview()
                make.left.equalToSuperview().offset(CGFloat(i) * itemWidth)
                make.height.equalTo(menuHeight - 26)
            }
            menuItem.addTarget(self, action: #selector(menuItemClick(send:)), for: .touchUpInside)
        }
        
        addWavylineBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(35, 35))
            make.right.equalToSuperview().offset(-26)
            make.top.equalToSuperview()
        }
        
        addStraightLineBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(35, 35))
            make.right.equalTo(addWavylineBtn.snp.left).offset(-11)
            make.top.equalToSuperview()
        }
        
        addColorBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(35, 35))
            make.right.equalTo(addStraightLineBtn.snp.left).offset(-11)
            make.top.equalToSuperview()
        }
        
    }
    
    //空白地方 点击
    @objc func menubgTapClick(tap:UITapGestureRecognizer){
        if bgMenuTapBlock != nil {
           bgMenuTapBlock!()
        }
    }
    
    //MARK: -----------------------Action----------------------------
    @objc func menuItemClick(send:UIButton){
        let btntag = send.tag
        
        var menutype = NoetMenuType.write
        
        switch btntag {
        case 100: //笔记
            YLLog("笔记")
            menutype = .write
            
        case 101: //复制
            YLLog("复制")
            menutype = .copy
        case 102: //删除划线
            YLLog("删除划线")
            
            menutype = isDeleteLine ? .deLine : .line
            isDeleteLine = !isDeleteLine
            setLineState()
            
        case 103: //勘误
            YLLog("勘误")
            menutype = .errata
        default:
            YLLog("other")
        }
        
        if menutype == .deLine || menutype == .copy || menutype == .errata{
            hiddenMenu()
        }
        
        
        delegate?.noteMenu(menuControl: self, didSelectItem: menutype)
    }
    
    @objc func editTextClick(send:UIButton){
        let tagValue = send.tag
        var menutype = NoetMenuType.bg_color
        
        switch tagValue {
        case 1000:// 背景颜色
            menutype = .bg_color
            YLLog("背景颜色")
        case 1001:// 直线
            menutype = .solid_line
            YLLog("直线")
        case 1002:// 波浪线
            menutype = .wave_line
            YLLog("波浪线")
        default:
            YLLog("other")
        }
        
        for item in lineClickItems {
            if item.tag == tagValue {
                item.isSelected = true
            }else{
                item.isSelected = false
            }
        }

        NoteMenuController.lineType = menutype
        delegate?.noteMenu(menuControl: self, didSelectItem: menutype)
    }
    
    func setLineState(curLineType:NoetMenuType = .line){
        editTextView.isHidden = !isDeleteLine
        textLineItem.titleLab.text = isDeleteLine ? "删除划线" : "划线"
        textLineItem.topImageV.image = isDeleteLine ? UIImage(named: "note_icon_delete") : UIImage(named: "note_icon_white_line")
        
        
        switch curLineType {
        case .solid_line:
            addStraightLineBtn.isSelected = true
            addColorBtn.isSelected = false
            addWavylineBtn.isSelected  = false
        case .bg_color:
            addColorBtn.isSelected = true
            
            addStraightLineBtn.isSelected = false
            addWavylineBtn.isSelected  = false
        case .wave_line:
            addWavylineBtn.isSelected = true
            addColorBtn.isSelected = false
            addStraightLineBtn.isSelected = false
        default:
           YLLog("other")
        }
        
    }
    
    public func showMenuWithRect(rect:CGRect,isLined:Bool = false,linetype:NoetMenuType = .dotted_gobal_line){
        
        isDeleteLine = isLined
        var direction:NoteMenuArrowDirection = .down
        if rect.minY - NoteMenuController.menuSuperHeight - 5 < KsafeAreaNaviBarHeight {
            direction = .up
        }else {
            direction = .down
        }
        
        self.layoutIfNeeded()
        
        if direction == .down {
            self.snp.updateConstraints { make in
                make.top.equalToSuperview().offset(rect.origin.y - NoteMenuController.menuSuperHeight - 5 )
            }
            downArrowImageV.image = srcDownArrow
            
            downArrowImageV.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: 15, height: 7))
                make.bottom.equalToSuperview()
                make.left.equalToSuperview().offset(rect.origin.x - (15/2))
            }
            
            menuContentView.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: menuWidth, height: menuHeight))
                make.bottom.equalTo(downArrowImageV.snp.top)
                make.centerX.equalTo(downArrowImageV)
            }
            
            editTextView.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: menuWidth * 0.75, height: 50))
                make.bottom.equalTo(menuContentView.snp.top)
                make.right.equalTo(menuContentView)
            }
            
            updateEditTextViewConstraint(direction: direction)
             
            if rect.origin.x >= (menuWidth/2) &&  rect.origin.x <= self.yh_width - (menuWidth/2){
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV)
                }
            }else if rect.origin.x < (menuWidth/2) {
                let offsetx = (menuWidth/2) - rect.origin.x
                
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV).offset(offsetx)
                }
            }else {
                let offsetx = rect.origin.x - (self.yh_width - (menuWidth/2))
                
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV).offset(-offsetx)
                }
            }
        }else {
            self.snp.updateConstraints { make in
                make.top.equalToSuperview().offset(rect.maxY )
            }
            
            downArrowImageV.image = getFlipImage(srcImage: srcDownArrow)
            
            downArrowImageV.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: 15, height: 7))
                make.top.equalToSuperview()
                make.left.equalToSuperview().offset(rect.origin.x - (15/2))
            }
        
            menuContentView.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: menuWidth, height: menuHeight))
                make.top.equalTo(downArrowImageV.snp.bottom)
                make.centerX.equalTo(downArrowImageV)
            }
            
            editTextView.snp.remakeConstraints { make in
                make.size.equalTo(CGSize(width: menuWidth * 0.75, height: 50))
                make.top.equalTo(menuContentView.snp.bottom)
                make.right.equalTo(menuContentView)
            }
            
            updateEditTextViewConstraint(direction: direction)
            
            if rect.origin.x >= (menuWidth/2) &&  rect.origin.x <= self.yh_width - (menuWidth/2){
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV)
                }
            }else if rect.origin.x < (menuWidth/2) {
                let offsetx = (menuWidth/2) - rect.origin.x
                
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV).offset(offsetx)
                }
            }else {
                let offsetx = rect.origin.x - (self.yh_width - (menuWidth/2))
                
                menuContentView.snp.updateConstraints { make in
                    make.centerX.equalTo(downArrowImageV).offset(-offsetx)
                }
            }
            
        }
        
        var tempType = linetype
        if linetype != .dotted_gobal_line {
            tempType = NoteMenuController.lineType
        }
        
        setLineState(curLineType: tempType)
        UIView.animate(withDuration: 0.3) {
            self.isHidden = false
        }
    }

    public func hiddenMenu(){

        UIView.animate(withDuration: 0.3) {
            self.isHidden = true
        }

    }
    
    //180°旋转
    private func getFlipImage(srcImage:UIImage) -> UIImage {
        
        let flipImage =  UIImage(cgImage: srcImage.cgImage!, scale: srcImage.scale, orientation: .down)
        
        return flipImage
    }
    
    private func updateEditTextViewConstraint(direction:NoteMenuArrowDirection){
        
        var topMargin:CGFloat = 0
        
        if direction == .up {
            topMargin = 15
        }
        addWavylineBtn.snp.updateConstraints { make in
            make.top.equalToSuperview().offset(topMargin)
        }
        
        addStraightLineBtn.snp.updateConstraints { make in
            make.top.equalToSuperview().offset(topMargin)
        }
        
        addColorBtn.snp.updateConstraints { make in
            make.top.equalToSuperview().offset(topMargin)
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var menuContentView: UIView = {
        let contentv = UIView()
        contentv.backgroundColor = UIColor(hexString: "#3D3D3D")
        contentv.yh_cornerRadius = scaleHeight(14, true)
        self.addSubview(contentv)
        return contentv
    }()
    
    lazy var downArrowImageV: UIImageView = {
        let imagev = UIImageView(image: UIImage(named: "note_menu_downArrow"))
        self.addSubview(imagev)
        return imagev
    }()
    
    lazy var editTextView: UIView = {
        let editView = UIView()
        editView.isHidden = true
        self.addSubview(editView)
        return editView
    }()
    
    lazy var addColorBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor(hexString: "#3D3D3D")
        btn.yh_cornerRadius = 35/2
        btn.tag = 1000
        btn.addTarget(self, action: #selector(editTextClick(send:)), for: .touchUpInside)
        btn.setImage(UIImage(named: "note_icon_remove_color"), for: .normal)
        btn.setImage(UIImage(named: "note_icon_dye"), for: .selected)
        editTextView.addSubview(btn)
        lineClickItems.append(btn)
        return btn
    }()
    
    lazy var addStraightLineBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor(hexString: "#3D3D3D")
        btn.yh_cornerRadius = 35/2
        btn.tag = 1001
        btn.addTarget(self, action: #selector(editTextClick(send: )), for: .touchUpInside)
        btn.setImage(UIImage(named: "note_icon_white_line"), for: .normal)
        btn.setImage(UIImage(named: "note_icon_red_line"), for: .selected)
        editTextView.addSubview(btn)
        lineClickItems.append(btn)
        return btn
    }()
    
    lazy var addWavylineBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor(hexString: "#3D3D3D")
        btn.yh_cornerRadius = 35/2
        btn.tag = 1002
        btn.addTarget(self, action: #selector(editTextClick(send: )), for: .touchUpInside)
        btn.setImage(UIImage(named: "note_icon_white_wavy_line"), for: .normal)
        btn.setImage(UIImage(named: "note_icon_yellow_wave_line"), for: .selected)
        editTextView.addSubview(btn)
        lineClickItems.append(btn)
        return btn
    }()
    
    
}

class NoteMenuItem: UIButton {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        titleLab.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        topImageV.snp.makeConstraints { make in
//            make.size.equalTo(CGSize(width: 19, height: 19))
            make.bottom.equalTo(titleLab.snp.top).offset(-scaleHeight(7,true))
            make.centerX.equalToSuperview()
        }
        
    }
    
    func setImageSize(size: CGSize) {
        topImageV.snp.updateConstraints { make in
            make.size.equalTo(size)
        }
    }
    
    lazy var topImageV: UIImageView = {
        let imagev = UIImageView.init()
        self.addSubview(imagev)
        return imagev
    }()
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = ""
        lab.textColor = UIColor.init(hexString: "#FFFFFF")
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        self.addSubview(lab)
        return lab
    }()
    
}
